﻿using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using KJSyncXP.Extensions;
using KJSyncXP.Sqlite.Model;
using KJSyncXP.ViewModels;
using KJSyncXP.Views.pop;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;

public class SetSettingsViewModel : BaseViewModel
{
    private readonly log4net.ILog _logger;
    private readonly AppConfig _appConfig;

    // 声明命令
    public RelayCommand SelectFolderCommand { get; private set; }
    public RelayCommand CheckShiftCommand { get; private set; }
    public RelayCommand SetShiftCommand { get; private set; }
    public RelayCommand SaveConfigCommand { get; private set; }

    private readonly string _configPath = "Configs/Appconfig.json";


    // 直接持有单个 AppConfig 对象（而非集合）
    private AppConfig _appConfigData;
    public AppConfig AppConfigData
    {
        get => _appConfigData;
        set
        {
            _appConfigData = value;
            RaisePropertyChanged("AppConfigData"); // 通知UI属性变更
        }
    }

    public SetSettingsViewModel(log4net.ILog log, AppConfig appConfig)
    {
        _logger = log;
        _appConfig = appConfig;
        loadAppConfig();

        SelectFolderCommand = new RelayCommand(SelectFolder);
        SetShiftCommand = new RelayCommand(SetShift);
        SaveConfigCommand = new RelayCommand(SaveConfig);
    }

    public void loadAppConfig()
    {
        try
        {
            // 直接赋值单个 AppConfig 对象
            AppConfigData = _appConfig;
        }
        catch (Exception ex)
        {
            _logger.Warn("加载配置失败", ex);
        }
    }

    public void SelectFolder()
    {
        FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
        folderBrowserDialog.ShowDialog();        //这个方法可以显示文件夹选择对话框
        string directoryPath = folderBrowserDialog.SelectedPath;    //获取选择的文件夹的全路径名
    }



    public void SetShift()
    {
        var ShiftSet = new ShiftItemWindow();
        ShiftSet.ShowDialog();
    }


    public void SaveConfig()
    {
        try
        {
            var ConfigWrapper = new ConfigWrapper();
            ConfigWrapper.AppConfig = AppConfigData;
            string json = JsonConvert.SerializeObject(ConfigWrapper, Formatting.Indented);
            File.WriteAllText(_configPath, json);
            _logger.Info("配置保存成功");
        }
        catch (Exception ex)
        {
            _logger.Error("保存配置失败", ex);
        }
    }


}